package com.ruoyi.config

import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.github.binarywang.wxpay.config.WxPayConfig
import com.github.binarywang.wxpay.service.WxPayService
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl
import com.ruoyi.back.domain.WxPaySetting
import com.ruoyi.back.service.WxPaySettingService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

/**
 * @author Binary Wang
 */
@Configuration
@ConditionalOnClass(WxPayService::class)
@EnableConfigurationProperties(
    WxPayProperties::class
)
class WxPayConfiguration {

    @Autowired
    private lateinit var wxPayProperties: WxPayProperties

    @Autowired
    private lateinit var wxPaySettingService: WxPaySettingService


    @Bean
    @ConditionalOnMissingBean
    fun wxService(): WxPayService =
        WxPayServiceImpl().apply {
            config = WxPayConfig().apply {
                wxPaySettingService.getOne(KtQueryWrapper(WxPaySetting::class.java).last("limit 1"))
                    ?.let {
                        appId = it.appId
                        mchId = it.merchantNumber
                        mchKey = it.privateKey
                        keyPath = wxPayProperties.keyPath
                        apiV3Key = wxPayProperties.apiV3Key
                    }
                isUseSandboxEnv = false
            }
        }
}